import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.MIDIControl;

import suit.ui.Application;
import suit.ui.Box;
import suit.ui.Button;
import suit.ui.Entry;
import suit.ui.Label;
import suit.ui.Scale;
import suit.ui.Screen;
import suit.ui.themes.DefaultTheme;

public class NotePlayer extends Application {

	Label status = new Label("Loaded");

	Entry channel;
	Scale note;
	Scale velocity;

	private MIDIControl control;

	public NotePlayer() {

		Screen main = new Screen(new DefaultTheme());

		Box vbox = new Box(Box.Vert, true, 6);
		vbox.setBorderWidth(6);

		vbox.pack(status, true, true, 0);

		// Channel
		Label c = new Label("Channel:");
		c.setAlign(Label.BOTTOM | Label.LEFT);
		vbox.pack(c, true, true, 0);

		channel = new Entry("11");
		vbox.pack(channel, true, true, 0);

		// Note
		Label n = new Label("Note:");
		n.setAlign(Label.BOTTOM | Label.LEFT);
		vbox.pack(n, true, true, 0);

		note = new Scale(Scale.Horiz, 0, 127, 1, 60);
		vbox.pack(note, true, true, 0);

		// Velocity
		Label v = new Label("Velocity:");
		v.setAlign(Label.BOTTOM | Label.LEFT);
		vbox.pack(v, true, true, 0);

		velocity = new Scale(Scale.Horiz, 0, 127, 1, 127);
		vbox.pack(velocity, true, true, 0);

		// Send
		Button send = new Button("Play");
		send.connect(new Button.Pressed() {

			public void onPressed(Button source) {
				int ch = Integer.parseInt(channel.getText());
				int no = (int) note.getValue();
				int ve = (int) velocity.getValue();
				NoteSend.send(control, ch, no, ve);

			}
		});
		send.connect(new Button.Released() {

			public void onReleased(Button source) {
				int ch = Integer.parseInt(channel.getText());
				int no = (int) note.getValue();
				NoteSend.send(control, ch, no, 0);

			}
		});
		vbox.pack(send, true, true, 0);

		main.add(vbox);
		setScreen(main);

		try {
			control = NoteSend.init();
		} catch (Exception e) {
			status.setText(e.getMessage());
		}

	}

	public static class NoteSend {

		public static MIDIControl init() throws Exception {

			Player p = Manager.createPlayer(Manager.MIDI_DEVICE_LOCATOR);
			p.prefetch();
			MIDIControl mControl = (MIDIControl) p
					.getControl("javax.microedition.media.control.MIDIControl");

			if (mControl == null)
				throw new Exception("MIDIControl not available");

			return mControl;
		}

		public static void send(MIDIControl control, int ch, int no, int ve) {

			control.shortMidiEvent(MIDIControl.NOTE_ON | ch, no, ve);
		}
	}
}
